//app.js
import PublishRouter from './assets/js/publishRouter'
import EventListener from './assets/js/eventListener'

App({
  onLaunch: function () {
    
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'xxxxxx',
        traceUser: true,
      })
    }

    // 小程序全局参数
    this.global = {
      //授权状态
      auth: {
        'scope.userInfo': false
      },
      userInfo: '', // 用户信息
      phone: '', // 手机号码 - 系统自动保存用户上一次验证的手机号码
      dynamic: null, // 动态 - 新消息
      positionInfo: null // 用户的位置信息

    }

    // 创建发布页面的路由跳转
    this.publishRouter = new PublishRouter()

    // 创建全局事件监听器
    this.eventListener = new EventListener()

    // 获取动态信息
    this.getDynamic()
  },
  
  /**
   * 获取用户信息
   * @return {Promise}
   */
  getUserInfo () {
    let _this = this;
    return new Promise((resolve, reject) => {
      if (_this.global.userInfo) {
        resolve(_this.global.userInfo)
      } else {
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              _this.global.auth['scope.userInfo'] = true
              wx.getUserInfo({
                success: res => {
                  _this.global.userInfo = res.userInfo
                  resolve(res.userInfo)
                }, fail(err) {
                  resolve('error')
                }
              })
            } else {
              resolve()
            }
          }, fail(err) {
            resolve('error')
          }
        })
      }
    })
  },
  
  /**
   * 获取用户手机号码
   * @return {Promise}
   */
  getUserPhone () {
    return new Promise((resolve, reject) => {
      if (this.global.phone) {
        resolve(this.global.phone)
      } else {
        const _this = this
        wx.cloud.callFunction({
          name: 'queryUser',
          success (res) {
            const user = res.result.data && res.result.data[0]
            if (user) {
              _this.global.phone = user.phone
              resolve(user.phone)
            }
          },
          fail (err) {
            resolve('')
          }
        })
      }
    })
  },

  /**
   * 获取当前地址
   * @return {Promise}
   */
  getPositionInfo () {
    return new Promise((resolve, reject) => {
      if (this.global.positionInfo) {
        resolve(this.global.positionInfo)
      } else {
        const _this = this
        // 获取用户位置信息
        wx.getLocation({
          type: 'gcj02',
          async success (res) {
            const lon = res.longitude
            const lat = res.latitude
            // 获取用户地址信息
            _this.getAddressByPositon(lat, lon)
              .then(result => {
                _this.global.positionInfo = {
                  code: 0,
                  position: [lon, lat],
                  region: result.region,
                  address: result.address
                }
                resolve(_this.global.positionInfo)
              }).catch(err => {
                resolve({ code: -1, msg: '位置信息获取失败' })
              })
          }, fail (res) {
            wx.getSystemInfo({
              success (res) {
                if (!res.locationEnabled) {
                  resolve({ code: -1, msg: '请打开设备的位置信息' })
                } else {
                  resolve({ code: -1, msg: '位置信息获取失败' })
                }
              }, fail () {
                resolve({ code: -1, msg: '位置信息获取失败' })
              }
            })
          }
        })
      }
    })
  },

  /**
   * 根据经纬度获取当前地址
   * @param {Number} lat 经度
   * @param {Number} lon 纬度
   * @return {Promise}
   */
  getAddressByPositon (lat, lon) {
    return new Promise((resolve, reject) => {
      // 调用腾讯地图接口
      wx.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lon}&key=N3TBZ-AOUWW-7TBR5-RFY6E-RIQI5-22BSY`,
        timeout: 3000,
        success(res) {
          const {status, result} = res.data
          if (status === 0) {
            let { province, city, district, street, street_number } = result.address_component
            street_number = street_number === street ? '' : street_number

            // 部分地区的district没有值，需从address_reference中获取地区信息
            let townTitle = result.address_reference.town && result.address_reference.town.title
            district = district || townTitle

            resolve({
              region: [province, city, district],
              address: street + street_number
            })
          } else {
            reject()
          }
        }, fail (err) {
          reject()
        }
      })

      // pc端偶现request无反应的情况，即success、fail、complete都未被调用
      setTimeout(() => {
        reject()
      }, 3010)
    })
  },

  /**
   * 查询动态数量，并在“我的”tab项显示动态数量
   */
  getDynamic () {
    wx.cloud.callFunction({
      name: 'queryRequestNum'
    }).then(res => {
      const result = res.result
      this.global.dynamic = result
      if (result.total > 0) {
        wx.setTabBarBadge({
          index: 2,
          text: result.total.toString()
        })
      }
    })
  },

  /**
   * 格式化日期
   * @param {Number | String | Date} value 时间值，可以是时间戳、字符串或Date类型的值
   * @param {String} type 要获取的时间类型，date表示日期，time表示时间
   * @return {String} 特定格式的时间字符串
   */
  formatDate (value, type) {
    const date = new Date(value)
    const years = date.getFullYear()
    let months = date.getMonth() + 1
    let dates = date.getDate()
    let hours = date.getHours()
    let minutes = date.getMinutes()
    let seconds = date.getSeconds()

    months = months < 10 ? `0${months}` : months
    dates = dates < 10 ? `0${dates}` : dates
    
    if (type === 'date') {
      return `${years}-${months}-${dates}`
    } else if (type === 'time') {
      hours = hours < 10 ? `0${hours}` : hours
      minutes = minutes < 10 ? `0${minutes}` : minutes
      seconds = seconds < 10 ? `0${seconds}` : seconds
      return `${years}-${months}-${dates} ${hours}:${minutes}:${seconds}`
    }
  }
})
